<?php


namespace app\api\controller;


use app\api\model\CorpModel;
use app\api\model\MeetConfigModel;
use app\api\model\MeetModel;
use app\api\model\WorkModel;
use app\api\model\Wxconfig;
use app\common\controller\Api;
use app\common\library\Sms;
use app\common\library\WXBizMsgCrypt;
use function fast\e;
use fast\Random;
use think\Db;

class Userinfo extends Api
{
    protected $noNeedLogin = ['wxlogin','authUrl','applyid','callbackverify','openFileInit','huiyiverify','aa'];
    protected $noNeedRight = '*';

    public function openFileInit()
    {
        $url = input('url');
        if(empty($url)){
             $this->error('url必传');
        }
        $config = MeetConfigModel::config();
        $corpid = $config['corpid'];
        $secret = $config['Secret'];
        $AgentId = $config['AgentId'];
        $api_data = MeetConfigModel::getAccessToken($corpid,$secret);

        $noncestr = uniqid();
        $timestamp = time();
        $url = urldecode($url);
        $jsapi_ticket = MeetConfigModel::getTicket($api_data['access_token']);
        $signature = "jsapi_ticket=$jsapi_ticket&noncestr=$noncestr&timestamp=$timestamp&url=$url";
        $sign = sha1($signature);
        $data1 = [
            'corpid' => $corpid,
            'agentid' => $AgentId,
            'timestamp' => $timestamp,
            'nonceStr' => $noncestr,
            'signature' => $sign,
            //'jsApiList' => ['previewFile','chooseImage','previewImage','uploadImage','checkJsApi','agentConfig'],
            'jsApiList' => ['previewFile'],
            'url' => $url,
            'jsapi_ticket' => $jsapi_ticket,
        ];
        $jsapi_ticket = MeetConfigModel::getAppTicket($api_data['access_token']);
        $signature = "jsapi_ticket=$jsapi_ticket&noncestr=$noncestr&timestamp=$timestamp&url=$url";
        $sign = sha1($signature);
        $data2 = [
            'corpid' => $corpid,
            'agentid' => $AgentId,
            'timestamp' => $timestamp,
            'nonceStr' => $noncestr,
            'signature' => $sign,
            //'jsApiList' => ['previewFile','chooseImage','previewImage','uploadImage','checkJsApi','agentConfig'],
            'jsApiList' => ['previewFile'],
            'url' => $url,
            'jsapi_ticket' => $jsapi_ticket,
        ];
        $data = [
            'qiye' => $data1,
            'app' => $data2
        ];
        $this->success('成功',$data);
    }

    public function info()
    {
        $user = $this->auth->getUserinfo();
        $this->success('成功',$user);
    }

    public function applyid()
    {
        $data = [
            'huiyi_id' => MeetConfigModel::getId(3),
            'huodong_id' => MeetConfigModel::getId(4),
            'jiaoshi_id' => MeetConfigModel::getId(5),
            'gongzi_id' => MeetConfigModel::getId(6),
            'qingwai_id' => MeetConfigModel::getId(7),
        ];
        $this->success('成功',$data);
    }

    public function authUrl()
    {
        $url = '';
        $path = input('path');
        if($path){
            $url = urldecode($path);
        }
        $REDIRECT_URI = request()->domain().$url;
        //$REDIRECT_URI = 'https://huiyi.bigchun.com'.$url;
        //$REDIRECT_URI = 'https://work.bigchun.com';
        //echo $REDIRECT_URI.PHP_EOL;
        if(!empty($path)){
            $REDIRECT_URI = urlencode($REDIRECT_URI);
        }
        $config = MeetConfigModel::config();
        $corpid = $config['corpid'];
        $AGENTID = $config['AgentId'];
        $AGENTID = '1000035';
        $url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid='.$corpid.'&redirect_uri='.$REDIRECT_URI.'&response_type=code&scope=snsapi_privateinfo&state=STATE&agentid='.$AGENTID.'#wechat_redirect';
        $third_url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid='.$corpid.'&redirect_uri='.$REDIRECT_URI.'&response_type=code&scope=snsapi_privateinfo&agentid='.$AGENTID.'&state=STATE#wechat_redirect';
        $url = $third_url;
        $data = [
            'url' => $url,
        ];
        //https://open.weixin.qq.com/connect/oauth2/authorize?appid=ww377c91a81493c595&redirect_uri=https://huiyi.bigchun.com&response_type=code&scope=snsapi_privateinfo&state=STATE&agentid=1000011#wechat_redirect
        $this->success('成功',$data);
    }

    public function wxlogin()
    {
        $code = input('code');
        $config = MeetConfigModel::config();
      /*  $corpid = $config['corpid'];
        $secret = $config['Secret'];
        $AgentId = $config['AgentId'];*/
        $row = CorpModel::where("")->find();
        $corpid = $row['corpid'];
        $secret = $row['permanent_code'];
        $AgentId = '1000035';
        $api_data = MeetConfigModel::getAccessToken($corpid,$secret);
        $infourl = 'https://qyapi.weixin.qq.com/cgi-bin/user/getuserinfo?access_token='.$api_data['access_token'].'&code='.$code;
        $client = new \GuzzleHttp\Client();
        $result = $client->get($infourl)->getBody()->getContents();
        $infodata = json_decode($result, true);
        if($infodata['errmsg'] != 'ok'){
            log_print('获取userinfo出错');
            log_print($api_data);
            $this->error('获取用户信息错误1');
        }
        //print_r($infodata);
        if(!empty($infodata['user_ticket'])){
            $option = [
                'user_ticket' => $infodata['user_ticket'],
            ];
            $url = 'https://qyapi.weixin.qq.com/cgi-bin/user/getuserdetail?access_token='.$api_data['access_token'];
            $client = new \GuzzleHttp\Client();
            $res = $client->request('POST', $url, [
                'json' => $option,
            ]);
            $req = $res->getBody()->getContents();
            $detail = json_decode($req, true);
            //print_r($detail);die();
            log_print('getuserdetail');
            log_print($detail);
            if($detail['errmsg'] != 'ok'){
                log_print('获取getuserdetail出错');
                log_print($detail);
                $this->error('获取用户信息错误2');
            }
        }
        $avatar = $detail['avatar']; //拿到头像

        if(empty($detail['mobile'])){
            $mobile = $detail['userid'];
        }else{
            $mobile = $detail['mobile'];
        }
        $durl = 'https://qyapi.weixin.qq.com/cgi-bin/user/get?access_token='.$api_data['access_token'].'&userid='.$detail['userid']; //读取通讯录资料
        $client = new \GuzzleHttp\Client();
        $result = $client->get($durl)->getBody()->getContents();
        $wxuser = json_decode($result, true);
        log_print('$wxuser');
        log_print($wxuser);
        if($wxuser['errmsg'] != 'ok'){
            log_print('获取通讯录出错');
            log_print($wxuser);
            $this->error('获取用户信息错误3');
        }
        $name = $mobile;
        if(!empty($wxuser['name'])){
            $name = $wxuser['name'];
        }
        $user = \app\common\model\User::getByMobile($mobile);
        if ($user) {
            //如果已经有账号则直接登录
            $ret = $this->auth->direct($user->id);
        } else {
            $ext = [
                'avatar' => $avatar,
                'nickname' => $name,
                'username' => $detail['userid'],
                'wx_userid' => $detail['userid'],
                'AgentId' => $AgentId,
            ];
            $ret = $this->auth->register($mobile, Random::alnum(), '', $mobile, $ext);
        }
        if ($ret) {
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Logged in successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }


    public function callbackverify(){
        $encodingAesKey = "P8oQ8KVqb3303FORvH7HvIFstNLCOguOmR6l1DYV6bC";
        $token = "agcKoqdLcGuobKQ6VmgYxMfw";
        $receiveid = "ww377c91a81493c595";

        $wxcpt = new WXBizMsgCrypt($token, $encodingAesKey, $receiveid);

        $sVerifyMsgSig = $_GET['msg_signature'];
        $sVerifyTimeStamp = $_GET['timestamp'];
        $sVerifyNonce = $_GET['nonce'];
        $sVerifyEchoStr = $_GET['echostr'];

        $sEchoStr = "";
        $errCode = $wxcpt->VerifyURL($sVerifyMsgSig, $sVerifyTimeStamp, $sVerifyNonce, $sVerifyEchoStr, $sEchoStr);
        if ($errCode == 0) {
            log_print($sEchoStr);
        	// 验证URL成功
            return $sEchoStr;
        } else {
            log_print('回调失败');
            log_print("ERR: " . $errCode);
            return '回调失败';
        }
    }


    public function huiyiverify(){
        $receiveid = "ww377c91a81493c595";
        $token = "3Sb5Z1ApauQffpGDYD7G";
        $encodingAesKey = "ZlJbw4mLt4kmRYKqnQwsNcwDt9pNSHEol7UTFjwGmoR";
        $postStr = file_get_contents("php://input");
        if(request()->domain() == 'http://work.test'){
            /*$postStr = '<xml><ToUserName><![CDATA[dkca9b08a0e2d9d11b]]></ToUserName><Encrypt><![CDATA[sWlRjiBZPSYyf5afDIFirAzJNBxKeUREWLPiCgp7LYvdUp6wxrAnsI7OzTk6pYUM6IH0errH4fz2rWMMpQKvr8hIOR+R5zHC4vKqPDPfSd9PDlGFxTlfIGIkADG7mFxzo0PF4IfLV/UZrMjyoaUr9HMWOpDfRTAcO4qkUF8ljFDJAjgSGtPu9pOcIgViUgEVSI4c1KHdAaMC8CFazfouAbMdOsALN7/i4bKqThDbTgCagmlt91wS+Lgyk1VciEHNezri2bokRZeJrUSAiLAudZh45CGHEAfZMxgJDLpD/fuKmNnWuslE00vcakDiWDya+PkhaVypqCynt+dQcvsPWxVNsleqk2AjnzXT3z0K3ImUZPUQBfmpgwR7JZRc94f6]]></Encrypt><AgentID><![CDATA[]]></AgentID></xml>';
            echo '本地调试';*/
        }
        file_put_contents('huiyi.txt',date('Y-m-d H:i:s').PHP_EOL,FILE_APPEND);
        file_put_contents('huiyi.txt',$postStr.PHP_EOL,FILE_APPEND);
        file_put_contents('huiyi.txt','接到的post参数'.PHP_EOL,FILE_APPEND);
        if(!empty($postStr)){
            $receiveid = 'dkca9b08a0e2d9d11b';
            //$receiveid = 'wp9YL4EQAAtWcqk-Gthi0KYZrdQOkd-w';
        }
        //$receiveid = 'wp9YL4EQAAtWcqk-Gthi0KYZrdQOkd-w';
        //log_print('授权通知');
        //log_print(input());
        $wxcpt = new WXBizMsgCrypt($token, $encodingAesKey, $receiveid);
        $sVerifyMsgSig = $_GET['msg_signature'];
        $sVerifyTimeStamp = $_GET['timestamp'];
        $sVerifyNonce = $_GET['nonce'];
        $sVerifyEchoStr = isset($_GET['echostr'])?$_GET['echostr']:'';
       /* log_print('post过来的数据1');
        log_print($postStr);
        file_put_contents('1.txt',$postStr,FILE_APPEND);*/
        //echo $postStr;die();
       /* if( !empty($postStr) ){
            $postObj2 = Xml2Array($postStr);
        }*/
        $sMsg = '';
        if(!empty($postStr)){
            $errCode = $wxcpt->DecryptMsg($sVerifyMsgSig, $sVerifyTimeStamp, $sVerifyNonce, $postStr, $sMsg);
            log_print('解密后的数据');
            log_print($sMsg);
            $sMsgArray = Xml2Array($sMsg);
            log_print('解密后转为数组');
            log_print($sMsgArray);
            //print_r($sMsgArray);die();
            if(!empty($sMsgArray['InfoType']) && $sMsgArray['InfoType'] == 'suite_ticket'){
                $row=CorpModel::where('SuiteId',$sMsgArray['SuiteId'])->find();
                if(!empty($row)){
                    $row->suite_ticket = $sMsgArray['SuiteTicket'];
                    $row->ticket_time = date('Y-m-d H:i:s');
                    $row->ticket_json = json_encode($sMsgArray,JSON_UNESCAPED_UNICODE);
                    $row->save();
                }else{
                    $insert = [
                        'SuiteId' => $sMsgArray['SuiteId'],
                        'suite_ticket' => $sMsgArray['SuiteTicket'],
                        'ticket_time' =>  date('Y-m-d H:i:s'),
                        'ticket_json' => json_encode($sMsgArray,JSON_UNESCAPED_UNICODE),
                    ];
                    CorpModel::create($insert);
                }
            }
            //收到 AuthCode
            if(!empty($sMsgArray['InfoType']) && $sMsgArray['InfoType'] == 'reset_permanent_code'){
                $row = CorpModel::where("")->find();
                $suite_access_token = WorkModel::get_suite_token($row['suite_ticket']);
                WorkModel::get_permanent_code($suite_access_token,$sMsgArray['AuthCode'],'dkca9b08a0e2d9d11b');
            }
            if($errCode === 0){
                log_print('解密内容');
                log_print($sMsg);
                echo 'success';
                die(); //成功
            }else{
                log_print('回调失败33333');
                log_print("ERR: " . $errCode);
            }
            die();
        }
        $sEchoStr = '';
        $errCode = $wxcpt->VerifyURL($sVerifyMsgSig, $sVerifyTimeStamp, $sVerifyNonce, $sVerifyEchoStr, $sEchoStr);

        //var_dump($sEchoStr);
        if ($errCode === 0) {
            log_print($sEchoStr);
            // 验证URL成功
            //echo 'success';
            //die();
            return $sEchoStr;
            //return $sEchoStr;
        } else {
            log_print('回调失败');
            log_print("ERR: " . $errCode);
            return '回调失败';
        }
    }
    //
    public function aa()
    {

      /*  $provider_access_token = WorkModel::get_provider_token();
        WorkModel::corpid_to_opencorpid($provider_access_token);*/
        $SuiteId = 'dkca9b08a0e2d9d11b';
        $row = CorpModel::where("")->find();
        $row = $row->toArray();
        //print_r($row['corp_text']);
        print_r(json_decode($row['corp_text'],true));

     /*   $suite_access_token = WorkModel::get_suite_token($row['suite_ticket']);
        $pre_auth_code = WorkModel::get_pre_auth_code($suite_access_token);
        print_r($pre_auth_code);*/
        //你好，自建应用待开发不需要安装第三方应用，授权企业扫码授权代开发模板可以获取临时授权码然后换取永久授权码，通过永久授权码换取accesstoken
        /**
        他回调过来是一个AuthCode，先通过AuthCode获取永久授权码permanent_code,这个时候就可以拿到企业的Corpid了，然后再根据这个Corpid匹配已授权的企业，把secret存储下来
         *
         */
    }

}
